import time
from selenium import webdriver
from selenium.common.exceptions import InvalidArgumentException, WebDriverException, NoSuchElementException
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

class Base:
    def __init__(self, browser):
        # 打开浏览器
        if browser == 'chrome':
            self.driver = webdriver.Chrome()
        elif browser == 'firefox':
            self.driver = webdriver.Firefox()
        elif browser == 'edge':
            self.driver = webdriver.Edge()
        else:
            print('不支持该浏览器')
            self.driver = None
        # 窗口最大化
        self.driver.maximize_window()

    def get(self, url):
        # 请求目标网址
        try:
            self.driver.get(url)
        except (InvalidArgumentException, WebDriverException):
            print('输入的地址不正确')
        # 元素等待
        self.driver.implicitly_wait(10)

    def find_element(self, locator):
        # 定位元素
        try:
            return self.driver.find_element(*locator)
        except NoSuchElementException:
            print('元素定位失败')

    def get_attribute(self,locator, value):
        # 获取元素属性
        object = self.find_element(locator)
        if object is None:
            print('元素定位失败')
        else:
            ojt = object.get_attribute(value)
            print(ojt)

    def send_keys(self, locator, value):
        sk = self.find_element(locator)
        if sk is not None:
            sk.send_keys(value)
        else:
            print('元素定位失败')

    def click(self, locator):
        # 元素点击操作
        element = self.find_element(locator)
        if element is None:
            print('元素定位失败')
        else:
            element.click()

    def forward(self):
        # 前进
        self.driver.forward()

    def back(self):
        # 后退
        self.driver.back()

    def refresh(self):
        # 刷新
        self.driver.refresh

    def quit(self):
        # 退出浏览器
        time.sleep(3)
        self.driver.quit()



if __name__ == '__main__':
    base = Base('chrome')
    base.get('https://www.baidu.com')
    base.find_element(('id', 'kw'))
    base.send_keys(('id', 'kw'), 'python')
    base.get_attribute(('id', 'kw'),'outerHTML')
    time.sleep(2)
    base.click((By.ID, 'su'))
    time.sleep(2)
    base.back()
    time.sleep(2)
    base.forward()
    time.sleep(2)
    base.refresh()
    time.sleep(2)
    base.quit()


